const Koa = require('koa');
const Router = require('koa-router');
const static = require('koa-static');
const path = require('path');
const fs = require('fs').promises;

const app = new Koa();


const router = new Router();

const SIZE = 5 * 1024 * 1024;

router.get('/video/:name', async ctx => {
    const {
        name
    } = ctx.params;
    const {
        block = 0
    } = ctx.query;

    const fp = await fs.open(path.resolve(__dirname, 'static', name));

    const {
        buffer,
        bytesRead
    } = await fp.read(Buffer.alloc(SIZE), 0, SIZE, SIZE * block)


    ctx.status = 200;
    ctx.set('content-type', 'video/mp4');
    ctx.set('content-length', bytesRead);
    ctx.body = buffer;

    fp.close();

})

app.use(static('./static'));
app.use(router.routes());

app.listen(8080, () => {
    console.log('server is run at 8080....')
})